<?php

/**
 * This file is part of the Framework03 PHP framework.
 * @author Walter Tamboer
 * @package Framework03
 */

/**
 * The Ini configuration reader and writer.
 */
class FW_Config_Ini extends FW_Config
{
    public function __construct($filename, $section = null, $allowModifications = false)
    {
        if (empty($filename))
            throw new FW_Config_Exception('Filename is not set.');

        if (!is_file($filename))
            throw new FW_Config_Exception("File '$filename' cannot be found.");
			
		$config = parse_ini_file($filename, true);

        $data = array();

        if ($section !== null)
        {
            if (!isset($config[$section]))
                throw new FW_Config_Exception("Section '$section' cannot be found in $filename.");

            $data = $this->getDataFromSection($config, $section);
        }
		
		// Now we split up the key names on the dot.
		$data = $this->splitChildren($data);
        
        parent::__construct($data);
    }

    private function getDataFromSection(array $config, $section)
    {
        if (!$config[$section])
            throw new FW_Config_Exception("Section '$section' cannot be found");

        $element = $config[$section];

        $data = array();

        if (isset($element[ 'extends' ]))
            $data = $this->getDataFromSection($config, $element[ 'extends' ]);

        return $this->mergeArrays($data, $element);
	}
	
	private function splitChildren(array $config)
	{
		$result = array();
		foreach ($config as $key => $value)
		{
			$index = strpos($key, '.');
			
			if ($index > 0)
			{
				$section = substr($key, 0, $index);
				$setting = substr($key, $index + 1);
				
				if (!isset($result[$section]))
					$result[$section] = array();
					
				$result[$section][$setting] = $value;
			}
			else
			{
				$result[$key] = $value;
			}
		}
		return $result;
	}
}
